<?php
namespace service\services;

use service\org\util\TpString;
use service\algo\AlgoLogic;
use  think\Db;
use  think\Log;
use think\Cache;

class QuestionService extends BaseQuestionService
{
    /**
     * 获取用户已经做过的试题.
     */
    public function getUserHasAnsweredQuestions($user_id, $topicId, $module_type)
    {
        if (!$user_id) {
            $user_id = $this->getUserId();
        }
        $where['user_id'] = $user_id;
        $where['topicId'] = $topicId;
        $where['module_type'] = $module_type;
        $userAnsweredQuestions = Db::name('user_exam_detail')->where($where)->select();
        $userAnsweredQuestionIds = array();
        foreach ($userAnsweredQuestions as $userAnsweredQuestion) {
            $userAnsweredQuestionIds[] = $userAnsweredQuestion['question_id'];
        }
        return $userAnsweredQuestionIds;
    }

    /**
     * 获取先行测试的下一个试题.
     * @param $topicId
     * @param $knowledge
     * @param $module
     * @param $used_type
     */
    public function getXianceNextQuestion($topicId, $knowledge, $module, $used_type)
    {
        $questions_list = $this->getQuestionsByKnowledge($knowledge, $module, $used_type);
        $questions_id_arr = array();
        foreach ($questions_list as $key => $val) {
            $questions_id_arr[] = $val['id'];
        }
        $hasAnsweredQuestionsId = $this->getUserHasAnsweredQuestions('', $topicId, $module);
        $not_answered_questionsId = array_diff($questions_id_arr, $hasAnsweredQuestionsId);
        $not_answered_questionsId_arr = array_merge($not_answered_questionsId, array());
        if (empty($not_answered_questionsId_arr)) {
            $num = count($questions_id_arr);
            $return_data['error'] = "题量不够出问题了,算法已推出,并且用户已做" . $num . "道题";
            Log::info("---111111------");
            Log::info($return_data['error']);
            Log::info("---111111------");
        } else {
            $next_question_id = $not_answered_questionsId_arr[0];
            //根据ID获取试题.
            Log::record("------before-------getQuestionById");
            $return_data = $this->getQuestionById($next_question_id);
            Log::record("------after-------getQuestionById");
            $return_data['error'] = "";
        }
        return $return_data;
    }


    /**
     * 提交试题
     */
    public function submitQuestion($topicId, $answer_content, $module_type, $tag_code, $used_type, $submodule_type = 0, $isViewAnalyze = 0)
    {
        $user_id = $this->getUserId();
        $return_data = array(
            'isSuccess' => 1,
            'is_right' => 0
        );
        $getQuestionTime = session("getQuestionTime");//获取取题时间
        foreach ($answer_content as $key => $q_info) {
            $question_id = $q_info['question_id'];
            $return_info = $this->compare_question($question_id, $q_info);
            $is_right = $return_info['is_right'];
            $right_answer = $return_info['right_answer'];
            $user_answer = $return_info['user_answer'];
            $isViewAnswer = empty($q_info['is_view_answer']) ? 0 : 1;
            $isViewAnalyze = 0;
            if (isset($q_info['is_view_analyze'])) $isViewAnalyze = $q_info['is_view_analyze'];
            //记录进入数据库,并记录入缓存中.
            Log::record("------before-------insertUserExamInfo");
            $this->insertUserExamInfo($topicId, $question_id, $return_info, $module_type, $used_type, $tag_code, $submodule_type, $isViewAnswer, $isViewAnalyze, $getQuestionTime);
            Log::record("------after-------insertUserExamInfo");
            //根据试题信息取出试题的难易度.
            $question_info = $this->getQuestionById($question_id);
            $diffculty = $question_info['difficulty'];
            $algoLogic = new AlgoLogic();
            // 只有边学边练的时候,会更新能力值.
            Log::record("------before-------updateAbility");
            if ($module_type == 2||$module_type==1) {
                $algoLogic->updateAbility($user_id, $tag_code, $diffculty, $is_right, $used_type, $topicId, $module_type);
            }
            Log::record("------after-------updateAbility");
            //更新用户的LOG.
            $this->updateUserExamActionLog("", $topicId, $module_type, $question_id);
            $return_data['is_right'] = $is_right;
        }
        return $return_data;
    }


    /**
     * 提交试题
     */
    public function redoSubmitQuestion($topicId, $answer_content, $module_type, $tag_code, $used_type, $submodule_type = 0, $isViewAnalyze = 0)
    {
        $user_id = $this->getUserId();
        $return_data = array(
            'isSuccess' => 1,
            'is_right' => 0
        );
        $getQuestionTime = session("getQuestionTime");//获取取题时间
        foreach ($answer_content as $key => $q_info) {
            $question_id = $q_info['question_id'];
            $return_info = $this->compare_question($question_id, $q_info);
            $is_right = $return_info['is_right'];
            $right_answer = $return_info['right_answer'];
            $user_answer = $return_info['user_answer'];
            $isViewAnswer = empty($q_info['is_view_answer']) ? 0 : 1;
            $isViewAnalyze = 0;
            if (isset($q_info['is_view_analyze'])) $isViewAnalyze = $q_info['is_view_analyze'];
            //记录进入数据库,并记录入缓存中.
            Log::record("------before-------insertUserExamInfo");
            $this->insertUserRedoExamInfo($topicId, $question_id, $return_info, $module_type, $used_type, $tag_code, $submodule_type, $isViewAnswer, $isViewAnalyze, $getQuestionTime);
//            Log::record("------after-------insertUserExamInfo");
//            //根据试题信息取出试题的难易度.
//            $question_info = $this->getQuestionById($question_id);
//            $diffculty = $question_info['difficulty'];
//            $algoLogic = new AlgoLogic();
//            // 只有边学边练的时候,会更新能力值.
//            Log::record("------before-------updateAbility");
//            if ($module_type == 2||$module_type==1) {
//                $algoLogic->updateAbility($user_id, $tag_code, $diffculty, $is_right, $used_type, $topicId, $module_type);
//            }
//            Log::record("------after-------updateAbility");
//            //更新用户的LOG.
//            $this->updateUserExamActionLog("", $topicId, $module_type, $question_id);
            $return_data['is_right'] = $is_right;
        }
        return $return_data;
    }


    /**
     * 判断试题的正确与否,并进行入库操作.
     * @param $question_id
     * @param array $user_answer = array(type=>1,answer=>"A");
     *
     */
    private function compare_question($question_id, $q_info)
    {
        $q_type = $q_info['type'];
        //q_type=1 表示单选题.q_type=2 ,表示是填空题.
        switch ($q_type) {
            case 1:
                $return_info = $this->compare_single_choice_question($question_id, $q_info);
                break;
            case 2:
                $return_info = $this->compare_blank_question($question_id, $q_info);
                break;
            case 3:
                $return_info = $this->compare_multiple_choice_question($question_id, $q_info);
                break;
            default:
                $return_info = array();
        }
        return $return_info;
    }


    /**
     * 单选题答案对比.
     */
    private function compare_single_choice_question($question_id, $q_info)
    {
        $question_info = $this->getQuestionById($question_id);
        $right_answer = $question_info['answer'];
//        $right_answer_base64 = $question_info['answer_base64'];
        $user_answer = $q_info['answer'];
        if ($right_answer == $user_answer) {
            $is_right = 1;
        } else {
            $is_right = 0;
        }
        $return_info['is_right'] = $is_right;
        $return_info['right_answer'] = json_encode($right_answer);
//        $return_info['right_answer_base64'] = json_encode($right_answer_base64);
        $return_info['user_answer'] = $user_answer;
//        $return_info['user_answer_base64'] = $q_info['answer_base64'];
        return $return_info;
    }

    /**
     * 暂时没有先不考虑
     * 多选题答案对比
     */
    private function compare_multiple_choice_question($question_id, $q_info)
    {
//        $question_info = $this->getQuestionById($question_id);
//        $right_answer  = $question_info['answer'];
//        $user_answer =  $q_info['user_answer'];
//        $return_info['is_right'] = 1;
//        $return_info['right_answer'] = "A";
//        $return_info['user_answer'] = "B";
    }

    /**
     * 填空题答案判断.
     */
    private function compare_blank_question($question_id, $q_info)
    {
        $question_info = $this->getQuestionById($question_id);
        $right_answer = $question_info['answer'];

        $right_answer_base64 = $question_info['answer_base64'];
        $user_answer_arr = explode(";", $q_info['answer']);
        $is_right = 0;
        $is_right_arr = array();
        foreach ($user_answer_arr as $key => $val) {
//            $val = trim($val);
            $val = str_replace("\, ", "", $val);
            $answer_html = $right_answer[$key];
            foreach ($answer_html as $key => $v) {
                $answer[$key] = htmlspecialchars_decode($v);
            }
            $format_answer = str_replace("\, ", "", $answer);
            if (in_array($val, $format_answer)) {
                $is_right_arr[] = 1;
            } else {
                $is_right_arr[] = 0;
            }
        }
        if (!in_array(0, $is_right_arr)) {
            $is_right = 1;
        }

        $return_info['is_right'] = $is_right;
        $return_info['right_answer'] = json_encode($right_answer);
        $return_info['right_answer_base64'] = json_encode($right_answer_base64);
        $return_info['user_answer'] = $q_info['answer'];
        $return_info['user_answer_base64'] = $q_info['answer_base64'];
        return $return_info;
    }


    /**
     * 插入试题数据.
     */
    private function insertUserExamInfo($topicId, $question_id, $return_info, $module_type, $used_type, $tag_code, $submodule_type, $isViewAnswer = 0, $isViewAnalyze = 0, $getQuestionTime = 0)
    {
        $user_id = $this->getUserId();
        $where['user_id'] = $user_id;
        $where['topicId'] = $topicId;
        $where['question_id'] = $question_id;
        $where['module_type'] = $module_type;
        $isHasAnswered = Db::name('user_exam_detail')->where($where)->find();

//        $gaoxiao_module_type = config("gaoxiao_module_type");
//        $xuexi_module_type = config("xuexi_module_type");
        $bxbl_module_type = config('bxbl_module_type');

        if ($isHasAnswered) {
            return;
        } else {
            if ($module_type == $bxbl_module_type) {
                $batch_num = $this->getNowBatchNum($topicId, $module_type);
            } else {
                $batch_num = 1;
            }

            $is_right = $return_info['is_right'];
            //如果查看过答案，也是错的
            if ($isViewAnswer == 1) {
                $is_right = 0;
            }
            $data = array(
                'user_id' => $user_id,
                'topicId' => $topicId,
                'batch_num' => $batch_num,
                'tag_code' => $tag_code,
                'module_type' => $module_type,
                'submodule_type' => $submodule_type,
                'used_type' => $used_type,
                'question_id' => $question_id,
                'right_answer' => $return_info['right_answer'],
                'user_answer' => $return_info['user_answer'],
                'right_answer_base64' => empty($return_info['right_answer_base64']) ? "" : $return_info['right_answer_base64'],
                'user_answer_base64' => empty($return_info['user_answer_base64']) ? "" : $return_info['user_answer_base64'],
                'is_right' => $is_right,
                'is_view_answer' => $isViewAnswer,
                'is_view_analyze' => $isViewAnalyze,
                'ctime' => time(),
                'stime' => $getQuestionTime,//获取试题时间

            );


            Db::name('user_exam_detail')->insert($data);
            $where_user_exam['user_id'] = $user_id;
            $where_user_exam['topicId'] = $topicId;
            $where_user_exam['module_type'] = $module_type;
            $where_user_exam['tag_code'] = $tag_code;

            $user_exam_info = Db::name('user_exam')->where($where_user_exam)->find();

            if ($user_exam_info) {
                //已有此数据,则进行错题喝和对题的数,还有时间的更新
                if ($is_right) {
                    $user_exam_data['right_num'] = $user_exam_info['right_num'] + 1;
                    $user_exam_data['utime'] = time();
                    Db::name('user_exam')->where($where_user_exam)->update($user_exam_data);
                } else {
                    $user_exam_data['wrong_num'] = $user_exam_info['wrong_num'] + 1;
                    $user_exam_data['utime'] = time();
                    Db::name('user_exam')->where($where_user_exam)->update($user_exam_data);
                }
            } else {
                $user_exam_data['user_id'] = $user_id;
                $user_exam_data['topicId'] = $topicId;
                $user_exam_data['module_type'] = $module_type;
                $user_exam_data['tag_code'] = $tag_code;
                $user_exam_data['ctime'] = time();
                $user_exam_data['batch_num'] = $batch_num;
                //如果没有,则插入此数据.如果有自动加一
                if ($is_right) {
                    $user_exam_data['right_num'] = 1;
                } else {
                    $user_exam_data['wrong_num'] = 1;
                }
                Db::name('user_exam')->insert($user_exam_data);
            }
        }
    }

    /**
     * 插入试题数据.
     */
    private function insertUserRedoExamInfo($topicId, $question_id, $return_info, $module_type, $used_type, $tag_code, $submodule_type, $isViewAnswer = 0, $isViewAnalyze = 0, $getQuestionTime = 0)
    {
        $user_id = $this->getUserId();
        $where['user_id'] = $user_id;
        $where['topicId'] = $topicId;
        $where['question_id'] = $question_id;
        $where['module_type'] = $module_type;
        $isHasAnswered = Db::name('user_exam_redo_detail')->where($where)->find();
//        $gaoxiao_module_type = config("gaoxiao_module_type");
//        $xuexi_module_type = config("xuexi_module_type");
        $bxbl_module_type = config('bxbl_module_type');

        if ($isHasAnswered) {
            return;
        } else {
            if ($module_type == $bxbl_module_type) {
                $batch_num = $this->getNowBatchNum($topicId, $module_type);
            } else {
                $batch_num = 1;
            }

            $is_right = $return_info['is_right'];
            //如果查看过答案，也是错的
            if ($isViewAnswer == 1) {
                $is_right = 0;
            }
            $data = array(
                'user_id' => $user_id,
                'topicId' => $topicId,
                'batch_num' => $batch_num,
                'tag_code' => $tag_code,
                'module_type' => $module_type,
                'submodule_type' => $submodule_type,
                'used_type' => $used_type,
                'question_id' => $question_id,
                'right_answer' => $return_info['right_answer'],
                'user_answer' => $return_info['user_answer'],
                'right_answer_base64' => empty($return_info['right_answer_base64']) ? "" : $return_info['right_answer_base64'],
                'user_answer_base64' => empty($return_info['user_answer_base64']) ? "" : $return_info['user_answer_base64'],
                'is_right' => $is_right,
                'is_view_answer' => $isViewAnswer,
                'is_view_analyze' => $isViewAnalyze,
                'ctime' => time(),
                'stime' => $getQuestionTime,//获取试题时间

            );


            Db::name('user_exam_redo_detail')->insert($data);
            $where_user_exam['user_id'] = $user_id;
            $where_user_exam['topicId'] = $topicId;
            $where_user_exam['module_type'] = $module_type;
            $where_user_exam['tag_code'] = $tag_code;

            $user_exam_info = Db::name('user_exam')->where($where_user_exam)->find();

            if ($user_exam_info) {
                //已有此数据,则进行错题喝和对题的数,还有时间的更新
                if ($is_right) {
                    $user_exam_data['right_num'] = $user_exam_info['right_num'] + 1;
                    $user_exam_data['utime'] = time();
                    Db::name('user_exam')->where($where_user_exam)->update($user_exam_data);
                } else {
                    $user_exam_data['wrong_num'] = $user_exam_info['wrong_num'] + 1;
                    $user_exam_data['utime'] = time();
                    Db::name('user_exam')->where($where_user_exam)->update($user_exam_data);
                }
            } else {
                $user_exam_data['user_id'] = $user_id;
                $user_exam_data['topicId'] = $topicId;
                $user_exam_data['module_type'] = $module_type;
                $user_exam_data['tag_code'] = $tag_code;
                $user_exam_data['ctime'] = time();
                $user_exam_data['batch_num'] = $batch_num;
                //如果没有,则插入此数据.如果有自动加一
                if ($is_right) {
                    $user_exam_data['right_num'] = 1;
                } else {
                    $user_exam_data['wrong_num'] = 1;
                }
                Db::name('user_exam')->insert($user_exam_data);
            }
        }
    }








    /**
     * 获取用户最后一条没做过的题信息.
     * @param $topicId
     * @param $module_type
     * @param null $userId
     */
    public function getLastUserExamActionLog($topicId, $module_type, $userId = null)
    {
        if (!$userId) {
            $user_id = $this->getUserId();
        }

        $where['user_id'] = $userId;
        $where['topicId'] = $topicId;
        $where['module_type'] = $module_type;
        $where['is_submit'] = 0;  //表示用户没有做.
        $return_data = Db::name('user_exam_action_log')->where($where)->order("id desc")->find();
        return $return_data;
    }

    /**
     * 插入用户的组题记录
     * @param $topicId
     * @param $module_type
     * @param $question_id
     * @param $return_data
     * @param $tag_code
     * @param null $userId
     */
    public function insertUserExamActionLog($user_id = null, $topicId, $module_type, $question_id, $question_info, $tag_code, $is_submit = 0)
    {
        if (!$user_id) {
            $user_id = $this->getUserId();
        }
        $serialize_questionInfo_data = serialize($question_info);
        $where['user_id'] = $user_id;
        $where['topicId'] = $topicId;
        $where['module_type'] = $module_type;
        $where['question_id'] = $question_id;
        $where['is_submit'] = $is_submit;
        $return_data = Db::name('user_exam_action_log')->where($where)->order("id desc")->find();
        if (!$return_data) {
            $user_exam_action_log_data['user_id'] = $user_id;
            $user_exam_action_log_data['module_type'] = $module_type;
            $user_exam_action_log_data['question_id'] = $question_id;
            $user_exam_action_log_data['topicId'] = $topicId;
            $user_exam_action_log_data['tag_code'] = $tag_code;
            $user_exam_action_log_data['question_info'] = $serialize_questionInfo_data;
            Db::name('user_exam_action_log')->insert($user_exam_action_log_data);
        }
    }


    /**
     * 更新用户的做题的试题状态.
     */
    public function updateUserExamActionLog($user_id = null, $topicId, $module_type, $question_id)
    {
        if (!$user_id) {
            $user_id = $this->getUserId();
        }
        $where['user_id'] = $user_id;
        $where['topicId'] = $topicId;
        $where['module_type'] = $module_type;
        $where['question_id'] = $question_id;
        $user_exam_action_log_data['is_submit'] = 1;
        Db::name('user_exam_action_log')->where($where)->update($user_exam_action_log_data);
    }


    /**
     * @param $tag_code
     * @param $module_type
     * @param $used_type
     */
    public function getBxblNextQuestion($user_id, $tag_code, $module_type, $used_type, $topicId)
    {
        $extraQuestions = $this->getBxblQuestions($user_id, $tag_code, $module_type, $used_type, $topicId);
        $next_question_id = $extraQuestions[0];
//        $next_question_id = "57dde02ba66d2001f6229211";
//        $next_question_id ="57de608c14fef93f24446e04";
        Log::record("------before----getBxblNextQuestion---getQuestionById");
        $return_data = $this->getQuestionById($next_question_id);
        Log::record("------after----getBxblNextQuestion---getQuestionById");
        Log::record("------return_data------" . json_encode($return_data));
//        $return_data['error'] = "";
        return $return_data;
    }

    /**
     * 获取用户边学边练要做的题.
     * @param $user_id
     * @param $tag_code
     * @param $module_type
     * @param $used_type
     * @param $topicId
     * @return mixed
     */
    public function getBxblQuestions($user_id, $tag_code, $module_type, $used_type, $topicId)
    {
        if (!$user_id) {
            $user_id = $this->getUserId();
        }
        //用户已经做过的题.
        $hasAnsweredQuestionsId = $this->getUserHasAnsweredQuestions($user_id, $topicId, $module_type);
        $question_list = $this->getQuestionsByKnowledge($tag_code, $module_type, $used_type);
        $extraQuestions = array();
        $i = 0;
        foreach ($question_list as $key => $val) {
            if (!in_array($val['id'], $hasAnsweredQuestionsId)) {
                $extraQuestions[$i]["id"] = $val['id'];
                $extraQuestions[$i]["difficulty"] = $val['difficulty'];
                $i++;
            }
        }
        if (!empty($extraQuestions)) {
            //调用算法筛题.
            $algoLogic = new AlgoLogic();
            $question_ids = $algoLogic->chooseQuestionsByAlgo("", $tag_code, $extraQuestions, $topicId);
            if (empty($question_ids)) {
                exit("算法错误---------算法未返回知识点.");
            }
        } else {
            exit("知识点取不到题,有BUG");
        }
        return $question_ids;
    }


    /**
     * 是否已经调用算法,获取到某个知识点边学边练下要做的题.
     */
    public function getQuestionsForBxblByTagCode($tag_code)
    {
        $user_id = $this->getUserId();
        $type = 1;  //边学边练的练习过程是1,堂堂清是2.
        $where['user_id'] = $user_id;
        $where['tag_code'] = $tag_code;
        $where['type'] = $type;
        $return_info = Db::name('user_bxbl_question')->where($where)->find();
        return $return_info;
    }


    /**
     * 插入用户边学边练的要做的试题.
     */
    public function insertUserBxblQuestion($user_id = null, $tag_code, $question_ids = array(), $topicId, $type = 1)
    {
        if ($user_id) {
            $user_id = $this->getUserId();
        }
        $return_data = $this->getQuestionsForBxblByTagCode($tag_code);

        $module_type = config('gaoxiao_module_type');
        $batch_num = $this->getBatchNum($topicId, $module_type);

        if (empty($return_data)) {

            Log::record("------batch_num-----" . $batch_num . "-----batch_num");
            $data['user_id'] = $user_id;
            $data['tag_code'] = $tag_code;
            $data['topicId'] = $topicId;
            $data['type'] = $type;
            $data['question_ids'] = json_encode($question_ids);
            $data['batch_num'] = $batch_num;
            Db::name('user_bxbl_question')->insert($data);
        }
    }


    /**
     * 获取当前应该的批次。主要用在提交时候。
     */
    public function getNowBatchNum($topicId,$module_type)
    {
        $user_id = $this->getUserId();
        $batch_num = $this->getBatchNum($topicId,$module_type);
        $detect_is_end = $this->getUserDetectIsEnd($user_id, $topicId, $batch_num);

        if($detect_is_end)
        {
            $batch_num = $batch_num +1;
        }
        return $batch_num;
    }





    /**
     * 获取用户取题
     *
     */
    public function getBatchNum($topicId, $module_type)
    {
        $user_id = $this->getUserId();
        $getUserHasAchieveTagCode = $this->getUserHasAchieveTagCode($topicId, $module_type);
        $has_get_num = count($getUserHasAchieveTagCode);
        if ($has_get_num != 0) {
            Log::record("------has_get_num-------" . $has_get_num . "-----has_get_num");
            $batch_num = ceil($has_get_num / 3);
//            //判断用户当前循环下堂堂清有没有做完.
//            $where['user_id'] = $user_id;
//            $where['topicId'] = $topicId;
//            $where['module_type'] = $module_type;
//            $return_data = Db::name('user_exam_detail')->where($where)->select();
//            $has_learned_num = count($return_data);
//


//            $return_data = Db::name('user_bxbl_ttq_question')->where($where)->find();
//            if($return_data['is_end'])
//            {
//                $batch_num = $num + 1;  //有点绕,需要好好理解下.
//            }else{
//                if($num!=0)
//                {
//                    $batch_num = $num ;  //有点绕,需要好好理解下.
//                }else{
//                    $batch_num = 1;
//                }
//            }

        } else {
            $batch_num = 1;
        }

        return $batch_num;
    }

//    /**
//     * 获取堂堂清的batch_num
//     */
//    public function getTtqBatchNum($topicId, $module_type)
//    {
//        $user_id = $this->getUserId();
//        $where['user_id'] = $user_id;
//        $where['topicId'] = $topicId;
//        $return_info = Db::name('user_bxbl_ttq_question')->where($where)->order("id desc ")->find();
//        if (!empty($return_info)) {
//            if ($return_info['is_end']) {
//                $batch_num = $return_info['batch_num'] + 1;
//            } else {
//                $batch_num = $return_info['batch_num'];
//            }
//        } else {
//            $batch_num = 1;
//        }
//
//        return $batch_num;
//    }


    /**
     * 获取用户已经获取过知识点的边学边练的知识点.
     * @param $topicId
     * @param $module_type
     */
    public function getUserHasAchieveTagCode($topicId, $module_type)
    {
        $user_id = $this->getUserId();
        $where['user_id'] = $user_id;
        $where['topicId'] = $topicId;
        $where['module_type'] = $module_type;
        $answeredInfo = Db::name('user_exam')->where($where)->order("id desc")->select();
        return $answeredInfo;
    }


    public function isEnterToTtq($user_id = null, $topicId, $module_type)
    {
        if (!$user_id) {
            $user_id = $this->getUserId();
        }
        $batch_num = $this->getBatchNum($topicId, $module_type);
        //先计算本批次的边学边练前部分有没有做完.
        $bxbl_front_is_end = $this->getUserBxblFrontIsEnd($user_id, $topicId, $batch_num, $module_type);
        //计算堂堂清此部分有没有做完.
        $bxbl_ttq_is_end = $this->getUserBxblTtqIsEnd($user_id, $topicId, $batch_num, $module_type);
        if ($bxbl_ttq_is_end && $bxbl_front_is_end) {
            $is_enter = 0;
        } elseif (!$bxbl_ttq_is_end && !$bxbl_front_is_end) {
            $is_enter = 0;
        } elseif ($bxbl_front_is_end && !$bxbl_ttq_is_end) {
            $is_enter = 1;
        } else {
            $is_enter = 0;
        }
        return $is_enter;
    }


    /**
     * 判断是否进入学习检测。
     * @param null $user_id
     * @param $topicId
     * @param $module_type
     */
    public function isEnterToDetect($user_id = null, $topicId, $module_type)
    {
        if (!$user_id) {
            $user_id = $this->getUserId();
        }
        $batch_num = $this->getBatchNum($topicId, $module_type);
        //判断用户本批次的高效学习是否完成。
        $gaoxiao_is_end = $this->getUserGaoxiaoIsEnd('', $topicId, $batch_num, $module_type);

        $detect_is_end = $this->getUserDetectIsEnd($user_id, $topicId, $batch_num);

        if ($detect_is_end && $gaoxiao_is_end) {
            $is_enter = 0;
        } elseif (!$detect_is_end && !$gaoxiao_is_end) {
            $is_enter = 0;
        } elseif ($gaoxiao_is_end && !$detect_is_end) {
            $is_enter = 1;
        } else {
            $is_enter = 0;
        }
        return $is_enter;
    }


    /**
     * 获取用户高效学习的知识点。
     * @param $user_id
     * @param $topicId
     * @param $batch_num
     * @param $module_type
     */
    private function getUserGaoxiaoIsEnd($user_id, $topicId, $batch_num, $module_type)
    {

        if (!$user_id) {
            $user_id = $this->getUserId();
        }
        $where['user_id'] = $user_id;
        $where['topicId'] = $topicId;
        $where['batch_num'] = $batch_num;
        $where['module_type'] = $module_type;
        $user_exam_info = Db::name('user_exam')->where($where)->order("id desc")->select();


        if (!empty($user_exam_info)) {
            $num = count($user_exam_info);
            if ($num % 3 == 0) {
                $user_answered_list = Db::name('user_exam_detail')->where($where)->order("id desc")->select();
                $has_answered_num = count($user_answered_list);
                if ($has_answered_num >= 9) {
                    $is_end = 1;
                } else {
                    $is_end = 0;
                }
            } else {
                $is_end = 0;
            }
        } else {
            $is_end = 0;
        }
        return $is_end;
    }


//    private function getUserBxblFrontIsEnd($user_id, $topicId, $batch_num, $module_type)
//    {
//        if (!$user_id) {
//            $user_id = $this->getUserId();
//        }
//        $where['user_id'] = $user_id;
//        $where['topicId'] = $topicId;
//        $where['batch_num'] = $batch_num;
//        $user_bxbl_question_info = Db::name('user_bxbl_question')->where($where)->order("id desc")->select();
//        if (!empty($user_bxbl_question_info)) {
//            $num = count($user_bxbl_question_info);
//            if ($num % 3 == 0) {
//                $last_tag_code = $user_bxbl_question_info[0]['tag_code'];
//
//                $where_detail['user_id'] = $user_id;
//                $where_detail['topicId'] = $topicId;
//                $where_detail['module_type'] = $module_type;
//                $where_detail['tag_code'] = $last_tag_code;
//                $where_detail['submodule_type'] = 1;
//                $answer_detail = Db::name('user_exam_detail')->where($where_detail)->select();
//                $answer_num = count($answer_detail);
//                if ($answer_num < 3) {
//                    Log::record("------" . __FUNCTION__ . "-------333");
//                    $bxbl_front_is_end = 0;
//                } else {
//                    Log::record("------" . __FUNCTION__ . "-------444");
//                    $bxbl_front_is_end = 1;
//                }
//            } else {
//                Log::record("------" . __FUNCTION__ . "-------555");
//                $bxbl_front_is_end = 0;
//            }
//        } else {
//            $bxbl_front_is_end = 0;
//        }
//        return $bxbl_front_is_end;
//    }


    private function getUserBxblTtqIsEnd($user_id, $topicId, $batch_num, $module_type)
    {
        if (!$user_id) {
            $user_id = $this->getUserId();
        }
        $where['user_id'] = $user_id;
        $where['topicId'] = $topicId;
        $where['batch_num'] = $batch_num;
        $return_data = Db::name('user_bxbl_ttq_question')->where($where)->find();
        if (!empty($return_data)) {
            $bxbl_ttq_is_end = $return_data['is_end'];
        } else {
            $bxbl_ttq_is_end = 0;
        }
        return $bxbl_ttq_is_end;
    }


    private function getUserDetectIsEnd($user_id, $topicId, $batch_num)
    {

        if (!$user_id) {
            $user_id = $this->getUserId();
        }
        $where['user_id'] = $user_id;
        $where['topicId'] = $topicId;
        $where['batch_num'] = $batch_num;
        $return_data = Db::name('user_bxbl_detect_question')->where($where)->find();
        if (!empty($return_data)) {
            $bxbl_detect_is_end = $return_data['is_end'];
        } else {
            $bxbl_detect_is_end = 0;
        }
        return $bxbl_detect_is_end;
    }


    public function getKnowledgeListByKmap()
    {
        $question_service = new QuestionService();
        $all_knowledgeList = $question_service->getKnowledgeList();
        $kmap_code = config("kmap_code");
        $module_type = config('xiance_module_type');
        $knowledgeList = $all_knowledgeList[$kmap_code];
        return $knowledgeList;

    }

    /**
     * 获取综合练习的下一道题的数据
     * @param type $module_type
     * @param type $used_type
     * @param type $topicId
     * @return type
     */
    public function getZhlxNextQuestion($module_type, $used_type = 2, $topicId)
    {
        $userInfo = session('userInfo');
        $user_id = $this->getUserId();
        $ttq_session_key = $user_id . "zhlx_num";
        $num = session($ttq_session_key);
        $question_list_key_val = '';
        $question_list = '';
        $question_list = $this->getZhlxQuestionIds();//获取当前知识点下有没有做错的 如果有就是继续做
        if ($question_list == false) $question_list = [];
        /******************埋点取得知识点第一个题id*********************/
        foreach ($question_list as $k => $v) {
            $first_user_exam_detail = Db::name("user_exam_detail")->where(['topicId' => $topicId, 'module_type' => $module_type, 'used_type' => $used_type, 'question_id' => $v[0]['id'], 'user_id' => $user_id])->field('right_answer_base64,user_answer_base64', true)->select();
            if (count($first_user_exam_detail) == 1 && $first_user_exam_detail[0]['is_right']) {
                unset($question_list[$k]);//删除组第一题答对的
            }
        }
        /******************埋点取得知识点第一个题id end*********************/
        $question_list_key_val = arr_foreachzh($question_list);//把二维数据换成一维
        $question_list = array_keys($question_list_key_val);
        $getUserHasAnsweredQuestions = $this->getUserHasAnsweredQuestions($user_id, $topicId, $module_type);//获取已经做过的题目
        //拿到用户做过的题的 问题id
        /*******************埋点循环比对判断当前答题列表的知识点和题id等于第一个知识并且做对的情况下清空同知识点下的所有试题id************************/
        /*******************埋点循环比对判断当前答题列表的知识点和题id等于第一个知识并且做对的情况下清空同知识点下的所有试题id end******************/
        $question_list = array_values(array_diff($question_list, $getUserHasAnsweredQuestions));
        $tag_code = '';
        $question_id = '';
        if (isset($question_list[0]) && isset($question_list_key_val[$question_list[0]])) {
            $tag_code = $question_list_key_val[$question_list[0]];
            $question_id = $question_list[0];
            session('tag_code', $tag_code);
        }
        return ['tag_code' => $tag_code, 'question_id' => $question_id];
    }

    /**
     * 获取堂堂清回答错误的问题
     * @param     $topicId
     * @param int $module_type
     * @param int $submodule_type
     *
     * @return mixed
     */
    public function getTTQError($topicId, $module_type = 2, $submodule_type = 2)
    {
        $user_id = $this->getUserId();
        $map['user_id'] = $user_id;
        $map['topicId'] = $topicId;
        $map['module_type'] = $module_type;
        $map['submodule_type'] = $submodule_type;
        $map['is_right'] = 0;
        $result = Db::name('user_exam_detail')->where($map)->order("id desc")->paginate(1000);//可能以后会用到分页，暂时全取出来
        $page = $result->render();
        $returnData["data"] = $result;
        $returnData["page"] = $page;
        return $returnData;

    }

    /**
     * 获取用户提交的答案是否正确
     * @param type $answer_content
     * @return type
     */
    public function getAnswerRight($answer_content)
    {
        $user_id = $this->getUserId();
        $is_right = 0;
        foreach ($answer_content as $key => $q_info) {
            $question_id = $q_info['question_id'];
            $return_info = $this->compare_question($question_id, $q_info);
            $is_right = $return_info['is_right'];
            $return_data['is_right'] = $is_right;
        }
        return $is_right;
    }

    public function getQuestionsByIds($question_arr_id = [])
    {
        $return = [];
        if ($question_arr_id) {
            foreach ($question_arr_id as $v) {
                $return[$v] = $this->getQuestionById($v);
            }
        }
        return $return;
    }

    public function allUserId()
    {
        $uid = Db::name('user')->column('username', 'id');
        return $uid;
    }

    public function getUseranswerExamDetail($user_id = 0, $module_type, $topicId, $limit)
    {
        $where['topicId'] = $topicId;
        if ($user_id) $where['user_id'] = $user_id;
        if ($module_type) $where['module_type'] = $module_type;
        $join = [
            ['user user', 'detail.user_id=user.id'],
        ];
        $data = Db::name('user_exam_detail')->alias('detail')->join($join)->where($where)->field('user.username,detail.*')->paginate($limit);
        $list = $data->toArray();
        $question_arr_id = [];
        $kmap_code = config('kmap_code');  //知识图谱
        if (isset($list['data']) && is_array($list['data'])) {
            foreach ($list['data'] as $k => $v) {
                $question_arr_id[] = $v['question_id'];
                $getKnowlegeCode = $this->getKnowlegeCode($kmap_code, $v['tag_code']);
                $list['data'][$k]['tag_code_title'] = $getKnowlegeCode['name'];
            }
        }
        $questionContent = $this->getQuestionsByIds($question_arr_id);
        $allUserId = $this->allUserId();
        $data = [
            'list' => $list,
            'page' => $data->render(),
            'question_content' => $questionContent,
            'alluserId' => $allUserId
        ];
        return $data;
    }

    public function getUseranswerExamDetailExport($user_id = 0, $module_type, $topicId)
    {
        $exclude = [
            'id',
            'user_id',
            'topicId',
            'tag_code',
            'module_type',
            'submodule_type',
            'used_type',
            'user_answer_base64',
            'is_view_answer',
            'right_answer',
            'is_view_analyze'
        ];
        $arr = [
            'username' => '用户名',
            'question_content' => '题目',
        ];
        $structure = StructureExport::getStructure(config('database.prefix') . 'user_exam_detail', $exclude);
        $structure = $arr + $structure;
        $where = ['topicId' => $topicId];
        if ($user_id) $where['user_id'] = $user_id;
        if ($module_type) $where['module_type'] = $module_type;
        $join = [
            ['user user', 'detail.user_id=user.id'],
        ];
        $data = Db::name('user_exam_detail')->alias('detail')->join($join)->where($where)->field('user.username,detail.*')->select();
        $question_arr_id = [];
        if ($data) {
            foreach ($data as $k => $v) {
                $question_arr_id[] = $v['question_id'];
            }
        }
        $questionContent = $this->getQuestionsByIds($question_arr_id);
        $return = [
            'list' => $data,
            'structure' => $structure,
            'question_content' => $questionContent
        ];
        return $return;
    }

    /**
     * 获取堂堂清待回答的知识点 数组
     */
    public function getTtqKnowledgeQuestionArr($topicId)
    {
        $TtqQuestionService = new TtqQuestionService();
        $getTtqQuestions = $TtqQuestionService->getTtqQuestions($topicId);//拿到所有待做题列表
        $data = [];
        $kmap_code = config('kmap_code');  //知识图谱
        foreach ($getTtqQuestions['tag_codes'] as $k => $v) {
            $data[$v]['question_id'][] = $getTtqQuestions['question_ids'][$k];
            $data[$v]['count'] = count($data[$v]['question_id']);
            if (isset($data[$v]['knowlegecode']) == false || $data[$v]['knowlegecode'] == false) $data[$v]['knowlegecode'] = $this->getKnowlegeCode($kmap_code, $v); //拿到知识点名称
        }
        return $data;
    }


    /**
     * 边学边练全部正确
     * @param $topicId
     * @param $tag_code
     *
     * @return bool
     */
    public function isAllRight($topicId, $tag_code)
    {
        $isAllRight = true;
        $user_id = $this->getUserId();
        $where['user_id'] = $user_id;
        $where['topicId'] = $topicId;
        $where['tag_code'] = $tag_code;
        $where['module_type'] = 2;
        $where['submodule_type'] = 1;

        $result = Db::name('user_exam_detail')->where($where)->where("is_right=0 or is_view_analyze=1")->fetchSql(false)->select();
        if ($result) {
            $isAllRight = false;
        }

        return $isAllRight;
    }

    /**
     * 获取试题的正答率
     * @param $question_id 试题id
     * @param $class_id 班级id
     */
    function getRightAnswerPercent($question_id,$topicId,$class_id,$user_id=null)
    {

        $where=[];
        if($question_id)
        {
            $where["question_id"]=$question_id;
        }
        if($topicId)
        {
            $where["topicId"]=$topicId;
        }

        if($class_id)
        {
            $where["class_id"]=$class_id;
        }

        if($user_id)
        {
            $where["user_id"]=$user_id;
        }

        $rightResult = Db::name('user_exam_detail')->where($where)->where("is_right=1 and  is_view_analyze=0 and is_view_answer=0")->count();
        $totalResult = Db::name('user_exam_detail')->where($where)->count();

        return [$rightResult,$totalResult];

    }

    /** 获取已经回答过的问题
     * @param null $user_id
     * @param $topicId
     * @param null $class_id
     * @param null $module_type
     * @return array
     */
    public function getHasAnsweredQuestions($user_id = null, $topicId, $class_id=null,$module_type=null)
    {

        $return_arr = array();
        $where=[];
       if($user_id)
       {
           $where['user_id'] = $user_id;
       }
        if($topicId)
        {
            $where['topicId'] = $topicId;
        }
        if($class_id)
        {
            $where['class_id'] = $class_id;
        }
        if($module_type)
        {
            $where['module_type'] = $module_type;
        }

        $answeredInfo = Db::name('user_exam_detail')->where($where)->group('question_id')->select();
        $question_service = new QuestionService();
        $kmap_code = config("kmap_code");
        foreach ($answeredInfo as $key => $val) {
//            $return_arr[$key]['question_id'] = $val['question_id'];
            $return_info = array();
            $return_info = $question_service->getQuestionById($val['question_id']);
            $return_info['tag_code'] = $val['tag_code'];
            $return_info['module_type'] = $val['module_type'];
            $return_info['right_answer'] = $val['right_answer'];
            $return_info['user_answer'] = $val['user_answer'];
            $return_info['stime'] = $val['stime'];
            $return_info['ctime'] = $val['ctime'];
            $tag = $question_service->getKnowlegeCode($kmap_code, $val['tag_code']);
            $return_info['tag_name'] = $tag["name"];
            $return_info['is_view_analyze'] = $val["is_view_analyze"];
            $return_info['is_view_answer'] = $val["is_view_answer"];
            $return_info['exam_detail_id'] = $val["id"];


            $return_info['right_answer_base64'] = $val['right_answer_base64'];

            // $return_info['user_answer_base64'] = $val['user_answer_base64'];

            $userAnswerBase64Arr = [];
            if ($val['user_answer_base64']) {
                $userAnswerBase64Arr = explode("@@@", $val['user_answer_base64']);
            }

            $return_info['user_answer_base64'] = $userAnswerBase64Arr;


            $return_info['is_right'] = $val['is_right'];
            $return_arr[] = $return_info;
        }

        return $return_arr;
    }


    /**
     * 通过id获取detail
     * @param $id
     * @return mixed
     */
    public function getHasAnsweredQuestionById($id)
    {
            $val = Db::name('user_exam_detail')->find($id);
            $question_service = new QuestionService();
            $kmap_code = config("kmap_code");
            $return_info = $question_service->getQuestionById($val['question_id']);
            $return_info['tag_code'] = $val['tag_code'];
            $return_info['module_type'] = $val['module_type'];
            $return_info['right_answer'] = $val['right_answer'];
            $return_info['user_answer'] = $val['user_answer'];
            $return_info['stime'] = $val['stime'];
            $return_info['ctime'] = $val['ctime'];
            $tag = $question_service->getKnowlegeCode($kmap_code, $val['tag_code']);
            $return_info['tag_name'] = $tag["name"];
            $return_info['is_view_analyze'] = $val["is_view_analyze"];
            $return_info['is_view_answer'] = $val["is_view_answer"];
            $return_info['right_answer_base64'] = $val['right_answer_base64'];
            // $return_info['user_answer_base64'] = $val['user_answer_base64'];
            $userAnswerBase64Arr = [];
            if ($val['user_answer_base64']) {
                $userAnswerBase64Arr = explode("@@@", $val['user_answer_base64']);
            }

            $return_info['user_answer_base64'] = $userAnswerBase64Arr;


            $return_info['is_right'] = $val['is_right'];

        return $return_info;
    }


    /**
     * 获取本题对错的学生ids
     * @param $question_id
     * @param $topicId
     * @param $class_id
     * @return array
     */
    public function getRightAndWrongUserIds($question_id,$topicId,$class_id)
    {
        if($topicId)
        {
            $where['topicId'] = $topicId;
        }
        if($class_id)
        {
            $where['class_id'] = $class_id;
        }
        if($question_id)
        {
            $where['question_id'] = $question_id;
        }
        $result = Db::name('user_exam_detail')->where($where)->select();
        $right=$wrong=[];

        foreach ($result as $item)
        {
            if($item["is_right"]==0 || $item["is_view_analyze"]==1 || $item["is_view_answer"]==1)
            {
               $wrong[]=$item["user_id"];
            }else
            {
                $right[]=$item["user_id"];
            }
        }

        return ["right"=>$right,"wrong"=>$wrong];
    }
    public function addErrorCorrection($data){
        return Db::name('error_correction')->insert($data);
    }
}
